package com.aiyige.utils;

import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.CountDownTimer;

import com.aiyige.configs.MyConfig;
import com.aiyige.model.SmsCode;
import com.aiyige.page.login.callbacks.ITimerCallBack;
import com.tencent.captchasdk.TCaptchaDialog;
import com.tencent.captchasdk.TCaptchaVerifyListener;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashSet;
import java.util.Set;

/**
 * 全局唯一的定时器
 * 可以根据需求用addCallback来控制或setCallback
 */
public class VerifyCodeManager {
    public SmsCode smsCode;
    public static final String TAG = VerifyCodeManager.class.getSimpleName();
    private static VerifyCodeManager mInstance;

    private Set<ITimerCallBack> callBackList = new HashSet<>();


    private ITimerCallBack loginCallBack;

    public ITimerCallBack getLoginCallBack() {
        return loginCallBack;
    }

    static MyCountDownTimer countDownTimer;

    public static boolean isStarting() {
        return starting;
    }

    public static void setStarting(boolean starting) {
        VerifyCodeManager.starting = starting;
    }

    static boolean starting = false;

    public void setLoginCallBack(ITimerCallBack loginCallBack) {
        this.loginCallBack = loginCallBack;
    }

    /**
     * 在发送状态时不允许remove回调，否则会报错
     */
    private boolean isSendStatus;

    /**
     * 登录管理 <BR>
     *
     * @return
     */
    public static synchronized VerifyCodeManager getInstance() {
        if (mInstance == null) {
            mInstance = new VerifyCodeManager();
        }
        return mInstance;
    }

    /**
     * 添加回调<BR>
     *
     * @param currentCallBack
     * @return
     */
    public boolean addLoginCallBack(ITimerCallBack currentCallBack) {
        return callBackList.add(currentCallBack);
    }

//    public SmsCode getSmsCode() {
//        return smsCode;
//    }

    /**
     * 当设置null时，表示清除计时器和回调
     * @param smsCode
     */
    public void setSmsCode(SmsCode smsCode) {
        this.smsCode = smsCode;
        if (smsCode == null) {
            cancel();
        }
    }

    /**
     * 外部无需监听回调时销毁callback
     *
     * @param callBack
     */
    public void removeLoginCallBack(ITimerCallBack callBack) {
        if (isSendStatus) {
            return;
        }
        if (callBackList == null) {
            return;
        }
        callBackList.remove(callBack);
    }

    private void sendOnTickCallback(long l) {
        isSendStatus = true;
        for (ITimerCallBack currentCallBack : callBackList) {
            currentCallBack.onTick(l);
        }
        isSendStatus = false;
    }

    private void sendOnFinishCallback() {
        isSendStatus = true;
        for (ITimerCallBack currentCallBack : callBackList) {
            currentCallBack.onFinish();
        }
        isSendStatus = false;
    }


    private class MyCountDownTimer extends CountDownTimer {

        public MyCountDownTimer(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        //计时过程
        @Override
        public void onTick(long l) {
            sendOnTickCallback(l);
        }

        //计时完毕的方法
        @Override
        public void onFinish() {
            sendOnFinishCallback();
            starting = false;
        }
    }

    public void start() {
        if (countDownTimer == null) {
            countDownTimer = new MyCountDownTimer(60000, 1000);
        }
        if (!starting) {
            countDownTimer.start();
            starting = true;
        }
    }

    public void cancel() {
        if (countDownTimer != null) {
            countDownTimer.cancel();
            starting = false;
        }
    }


    public void tCaptchaDialog(Context context,final TCaptchaCallBack callBack) {
        /**
         @param context，上下文
         @param appid，业务申请接入验证码时分配的appid
         @param listener，验证码验证结果回调
         @param jsonString，业务自定义参数
         */
         TCaptchaDialog dialog = new TCaptchaDialog(context, true, new Dialog.OnCancelListener() {
             @Override
             public void onCancel(DialogInterface dialogInterface) {

             }
         }, MyConfig.TCaptchaVerifyAppID, new TCaptchaVerifyListener() {
            @Override
            public void onVerifyCallback(JSONObject jsonObject) {
                int ret = -1;
                try {
                    ret = jsonObject.getInt("ret");
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                if(ret == 0) {
                    //验证成功回调
                    //jsonObject.getInt("ticket")为验证码票据
                    //jsonObject.getString("appid")为appid
                    //jsonObject.getString("randstr")为随机串
                    if (callBack != null) {
                        callBack.success();
                    }
                } else if(ret == -1001) {
                    //验证码首个TCaptcha.js加载错误，业务可以根据需要重试
                    //jsonObject.getString("info")为错误信息
                } else {
                    //验证失败回调，一般为用户关闭验证码弹框
                    if (callBack != null) {
                        callBack.failed();
                    }
                }
            }
        }, null);
        dialog.show();
    }


    public interface TCaptchaCallBack{
        void success();

        void failed();
    }

}
